package com.gateio.flutter.lib_furnace

import android.app.Application
import androidx.annotation.Keep
import com.gateio.flutter.lib_furnace.protocol.IGTFlutterHostDelegate
import com.gateio.flutter.lib_furnace.protocol.GTFlutterInitConfig
import com.gateio.flutter.lib_furnace.protocol.IGTFlutterEngineDelegate
import io.flutter.FlutterInjector

/**
 * Author: Shper
 * Created: 2023/2/13
 */
@Keep
object GTFlutterInitializer {

    // 初始化配置
    internal var initConfig: GTFlutterInitConfig = GTFlutterInitConfig()
    // Activity 和 Fragment 的 Delegate
    private var createHostDelegateFun: (() -> IGTFlutterHostDelegate?) = { null }
    // FlutterEngine 代理类
    internal var flutterEngineDelegate: IGTFlutterEngineDelegate? = null

    /**
     * 模块初始化方法
     */
    @JvmStatic
    fun init(application: Application, initConfig: GTFlutterInitConfig) {
        GTFlutterInitializer.initConfig = initConfig
        // 初始化 Flutter
        FlutterInjector.instance().flutterLoader().startInitialization(application)
        // 初始化引擎
        GTFlutter.initFlutterEngine(application, initConfig.preheatEngine)
    }

    fun getEntrypointArgsJson(extendMap: MutableMap<String, Any>? = null,
                              customDarkMode: Boolean? = null): String {
        return initConfig.toJsonString(extendMap, customDarkMode)
    }

    /**
     * 设置 Activity 和 Fragment 代理类
     */
    @JvmStatic
    fun setupHostDelegate(creationFunction: (() -> IGTFlutterHostDelegate)) {
        createHostDelegateFun = creationFunction
    }

    /**
     * 设置 FlutterEngine 代理类
     */
    @JvmStatic
    fun setFlutterEngineDelegate(delegate: IGTFlutterEngineDelegate) {
        flutterEngineDelegate = delegate
    }

    internal fun getHostDelegate(): IGTFlutterHostDelegate? {
        return createHostDelegateFun.invoke()
    }

}